package com.ktg.mes.wm.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.domain.Result;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.chanjet.content.GetVoucherContent;
import com.ktg.mes.chanjet.response.GetVoucherResponse;
import com.ktg.mes.chanjet.spi.ChanjetSpi;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.domain.MdProductBom;
import com.ktg.mes.md.domain.MdProductStatisticsBom;
import com.ktg.mes.md.domain.MdStatistics;
import com.ktg.mes.md.service.IMdItemService;
import com.ktg.mes.md.service.IMdProductBomService;
import com.ktg.mes.md.service.IMdProductStatisticsBomService;
import com.ktg.mes.md.service.IMdStatisticsService;
import com.ktg.mes.md.vo.QueryVo;
import com.ktg.mes.pro.domain.ProTask;
import com.ktg.mes.pro.service.IProTaskService;
import com.ktg.mes.pro.service.IProWorkorderService;
import com.ktg.mes.qc.domain.QcIqc;
import com.ktg.mes.qc.domain.QcIqcLine;
import com.ktg.mes.qc.service.IQcIqcLineService;
import com.ktg.mes.qc.service.IQcIqcService;
import com.ktg.mes.util.LGLeftJoinQueryWrapper;
import com.ktg.common.core.domain.model.SqlResult;
import com.ktg.mes.webSocket.NoticeWbsocketType;
import com.ktg.mes.webSocket.NoticeWebsocket;
import com.ktg.mes.webSocket.NoticeWebsocketResp;
import com.ktg.mes.wm.controller.vo.WmInStockVo;
import com.ktg.mes.wm.controller.vo.WmVoPicking;
import com.ktg.mes.wm.domain.*;
import com.ktg.mes.wm.service.*;
import com.ktg.system.service.ISysDictDataService;
import com.ktg.system.strategy.AutoCodeUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 物料入库单行Controller
 *
 * @author yinjinlu
 * @date 2022-05-22
 */
@RestController
@RequestMapping("/wm/itemrecptline")
public class WmItemRecptLineController extends BaseController
{
    @Autowired
    private IWmItemRecptLineService wmItemRecptLineService;

    @Autowired
    private IWmStockOutService wmStockOutService;

    @Autowired
    private IWmStockWillOutService wmStockWillOutService;
    @Autowired
    private IWmMaterialStockService wmMaterialStockService;
    @Autowired
    private IWmWarehouseService wmWarehouseService;

    @Autowired
    private IWmStorageLocationService wmStorageLocationService;

    @Autowired
    private IWmStorageAreaService wmStorageAreaService;

    @Autowired
    private IMdItemService mdItemService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IMdProductBomService mdProductBomService;

    @Autowired
    private IWmIssueHeaderService wmIssueHeaderService;
    @Autowired
    private IWmIssueLineService wmIssueLineService;
    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IProWorkorderService proWorkorderService;
    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Autowired
    private IMdProductStatisticsBomService mdProductStatisticsBomService;

    @Autowired
    private IMdStatisticsService mdStatisticsService;


    @Autowired
    private IQcIqcService iQcIqcService;

    @Autowired
    private IQcIqcLineService iQcIqcLineService;

    @Autowired
    private ChanjetSpi chanjetSpi;


    /**
     * 查询物料入库单行列表
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:list')")
    @GetMapping("/list")
    public Result<IPage<WmItemRecptLine>> list(WmItemRecptLine wmItemRecptLine,
                                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询收录生产警告警告列表",null,null);
        try {
            Map map = req.getParameterMap();
            LGLeftJoinQueryWrapper<WmItemRecptLine> queryWrapper = new LGLeftJoinQueryWrapper<>(wmItemRecptLine,req.getParameterMap(),pageNo,pageSize);
            queryWrapper.orderBy("\"materialsInDate\" DESC, \"lineId\"");
            IPage<JSONObject> pageList = wmStockOutService.lgPageMapList(queryWrapper);
            List<JSONObject> records = pageList.getRecords();
            records.stream().forEach(wm ->{
                MdItem item = mdItemService.getById((Long) wm.get("itemId"));
                if(item.getProcessProductId() != null ){
                    MdStatistics mdStatistics = mdStatisticsService.getById(item.getProcessProductId());
                    wm.put("processProductName",mdStatistics.getStatisticsName());
                }else{
                    wm.put("processProductName","");
                }
            });
            pageList.setRecords(records);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:list')")
    @GetMapping("/list2")
    public Result<Object> list2(WmItemRecptLine wmItemRecptLine,
                               @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                               HttpServletRequest req)
    {
        Page page = new Page(pageNo,pageSize);
        IPage<WmItemRecptLine> list =  wmItemRecptLineService.findList(page,wmItemRecptLine);
        List<WmItemRecptLine> records = list.getRecords();
        records.stream().forEach(line ->{
            Long recptId = line.getRecptId();
            QcIqc qc = new QcIqc();
            qc.setRecptId(recptId);
            qc.setType("1");
            List<QcIqc> qcIqcs1 = iQcIqcService.selectQcIqcList(qc);
            if(qcIqcs1.size() > 0){
                QcIqc gyIqc = qcIqcs1.get(0);
                QcIqcLine qcLine = new QcIqcLine();
                qcLine.setIqcId(gyIqc.getIqcId());
                List<QcIqcLine> qcIqcLines = iQcIqcLineService.selectQcIqcLineList(qcLine);
                gyIqc.setQcIqcLine(qcIqcLines);
                line.setGyiqcs(gyIqc);
            }
            qc.setType("2");
            List<QcIqc> qcIqcs2 = iQcIqcService.selectQcIqcList(qc);
            if(qcIqcs2.size() > 0){
                QcIqc pzIqc = qcIqcs2.get(0);
                QcIqcLine qcLine = new QcIqcLine();
                qcLine.setIqcId(pzIqc.getIqcId());
                List<QcIqcLine> qcIqcLines = iQcIqcLineService.selectQcIqcLineList(qcLine);
                pzIqc.setQcIqcLine(qcIqcLines);
                line.setPziqcs(pzIqc);
            }
        });
        return Result.OK(list);
    }


    /**
     * 物料入库单行的BOM入库列表
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:bomList')")
    @GetMapping("/bomList")
    public Result<IPage<WmItemRecptLine>> bomList(WmItemRecptLine wmItemRecptLine,
                                               @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                               HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询收录生产警告警告列表",null,null);
        try {
            MdProductBom mdProductBom = new MdProductBom();
            mdProductBom.setItemId(wmItemRecptLine.getItemId());
            mdProductBom.setEnableFlag("Y");
            List<MdProductBom> bomList = mdProductBomService.selectMdProductBomList(mdProductBom);

            IPage<JSONObject> pageList = null;
            if (bomList != null && bomList.size() > 0){
                String str = "";
                for (int i = 0; i < bomList.size(); i++) {
                    if (i == 0){
                        str = bomList.get(i).getBomItemId()+"";
                    }else {
                        str += ","+bomList.get(i).getBomItemId();
                    }
                }
                LGLeftJoinQueryWrapper<WmItemRecptLine> queryWrapper = new LGLeftJoinQueryWrapper<>(new WmItemRecptLine(),req.getParameterMap(),pageNo,pageSize);
                queryWrapper.whereOtherSql("and wm_item_recpt_line.item_id in ("+str+")");
                pageList = wmStockOutService.lgPageMapList(queryWrapper);
            }else {
                pageList = LGLeftJoinQueryWrapper.getIPageNull(null);
            }

            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 查询物料入库单行列表
     */
    @GetMapping("/selectList")
    public Result<IPage<WmItemRecptLine>> selectList(WmItemRecptLine wmItemRecptLine,
                                               @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                               HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询收录生产警告警告列表",null,null);
        try {
            Map map = req.getParameterMap();
            String inType_in = null;
            if (map != null && map.get("inType_in") != null){
                inType_in = ((String[]) map.get("inType_in"))[0].toString();
            }
            LGLeftJoinQueryWrapper<WmItemRecptLine> queryWrapper = new LGLeftJoinQueryWrapper<>(wmItemRecptLine,req.getParameterMap(),pageNo,pageSize);
            if (inType_in != null){
                queryWrapper.whereOtherSql("and quantity > 0 and in_type in ("+inType_in+")");
            }else {
                queryWrapper.whereOtherSql("and quantity > 0");
            }
            queryWrapper.orderBy("\"createTime\" DESC, \"lineId\"");
            IPage<JSONObject> pageList = wmStockOutService.lgPageMapList(queryWrapper);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 查询物料入库
     * @param vo
     * @return
     */
    @GetMapping("/selectStockList")
    public Result<IPage<Map>> selectStockList(QueryVo vo) {
        IPage<Map> maps = wmMaterialStockService.selectStockList(vo);
        return Result.OK(maps);
    }

    @GetMapping("/selectStockList2")
    public Result<Object> selectStockList2(QueryVo vo) throws ChanjetApiException {
        String code = vo.getItemCode();
        JSONObject codeObj = new JSONObject();
        codeObj.put("text",code);
        codeObj.put("value",code);
        List list = new ArrayList();
        list.add(codeObj);
        list.add(codeObj);
        JSONObject paramDic = new JSONObject();
        paramDic.put("Inventory.Code",list);
        GetVoucherContent content = new GetVoucherContent();
        content.setPageSize(vo.getPageSize());
        content.setPageIndex(vo.getPageNo() - 1);
        if(vo.getWarehouseId() != null && vo.getWarehouseId() > 0){
            JSONObject warehouseObj = new JSONObject();
            warehouseObj.put("text",vo.getWarehouseId());
            warehouseObj.put("value",vo.getWarehouseId());
            paramDic.put("Warehouse.ID",warehouseObj);
        }
        content.setParamDic(paramDic);
        if(vo.getRecptType() == 2){
            GetVoucherResponse response = chanjetSpi.findProductReceiveList(content);
            return Result.OK(chanjetSpi.converData(response.getData()));
        }else {
            GetVoucherResponse resp = chanjetSpi.findPurchaseReceiveList(content);
            return Result.OK(chanjetSpi.converData(resp.getData()));
        }
    }




    /**
     * 查询物料入库单行列表
     */
    @GetMapping("/bomListFromItemId")
    public Result<IPage<WmItemRecptLine>> bomListFromItemId(@RequestParam(name="itemId") Long itemId,
                                                              @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                             @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                             HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询收录生产警告警告列表",null,null);
        try {
            if (itemId == null && itemId < 1){
                return apiLog.ok("产品编号 不能为空");
            }

            MdProductStatisticsBom bom = new MdProductStatisticsBom();
            bom.setItemId(itemId);

            QueryWrapper<MdProductStatisticsBom> typeBomQueryWrapper = new QueryWrapper<>(bom);
            List<MdProductStatisticsBom> list = mdProductStatisticsBomService.list(typeBomQueryWrapper);
            if (list == null || list.size() == 0){
                return apiLog.ok("产品BOM为空");
            }
            String bomName = null;
            for (int i = 0; i < list.size(); i++) {
                if (i == 0){
                    bomName = "'"+list.get(i).getStatisticsName()+"'";
                }else {
                    bomName += ",'"+list.get(i).getStatisticsName()+"'";
                }
            }

            LGLeftJoinQueryWrapper<WmItemRecptLine> queryWrapper = new LGLeftJoinQueryWrapper<>(new WmItemRecptLine(),req.getParameterMap(),pageNo,pageSize);
            queryWrapper.whereOtherSql("and quantity > 0 and process_product_name in ("+bomName+")");
            queryWrapper.eq("wm_item_recpt_line","is_in_stock","1");
            queryWrapper.orderBy("\"createTime\" DESC, \"lineId\"");
            IPage<JSONObject> pageList = wmStockOutService.lgPageMapList(queryWrapper);

            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 导出物料入库单行列表
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:export')")
    @Log(title = "物料入库单行", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmItemRecptLine wmItemRecptLine)
    {
        List<WmItemRecptLine> list = wmItemRecptLineService.selectWmItemRecptLineList(wmItemRecptLine);
        ExcelUtil<WmItemRecptLine> util = new ExcelUtil<WmItemRecptLine>(WmItemRecptLine.class);
        util.exportExcel(response, list, "物料入库单行数据");
    }

    /**
     * 获取物料入库单行详细信息
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:query')")
    @GetMapping(value = "/{lineId}")
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId)
    {
        return AjaxResult.success(wmItemRecptLineService.selectWmItemRecptLineByLineId(lineId));
    }


    /**
     * 同步T6信息
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:syncStock')")
    @Log(title = "同步T6信息", businessType = BusinessType.UPDATE)
    @GetMapping("/syncStock")
    public AjaxResult syncStock()
    {
        try{
            wmItemRecptLineService.sysnStock();
        }catch (Exception e){
            NoticeWebsocket.sendMessage(new NoticeWebsocketResp<>(NoticeWbsocketType.Error,e.getLocalizedMessage()));
            return AjaxResult.error(e.getLocalizedMessage());
        }

        return toAjax(1);
    }


    /**
     * 新增物料入库单行
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:add')")
    @Log(title = "物料入库单行", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody WmItemRecptLine wmItemRecptLine)
    {
        return toAjax(wmItemRecptLineService.addWmItemRecptLine(wmItemRecptLine));
    }


    /**
     * 新增物料组装入库单行
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:addAssemble')")
    @Log(title = "新增物料组装入库单行", businessType = BusinessType.INSERT)
    @PostMapping("/addAssemble")
    @Transactional
    public AjaxResult addAssemble(@RequestBody WmItemRecptLine wmItemRecptLine)
    {
        wmItemRecptLine.setInType("3");
        return toAjax(wmItemRecptLineService.addWmItemRecptLine(wmItemRecptLine));

    }



    /**
     * 新增物料入库单行
     */
    @Log(title = "物料入库单行", businessType = BusinessType.INSERT)
    @PostMapping("/pdaAdd")
    @Transactional
    public AjaxResult pdaAdd(@RequestBody WmInStockVo stockVo, HttpServletRequest req)
    {
        String[] list = stockVo.getText().replace("；",";").split(";");

        MdItem mdItemFind = new MdItem();
        mdItemFind.setSpecification(list[1]);
        mdItemFind.setViscosity(list[3]);


        String pageTypeStr = list[7];
        if(pageTypeStr.contains("（软）")){
            mdItemFind.setItemName(list[2]+"软");
        }

        //生产日期
        String productDateStr = list[4];
        if(productDateStr  != null && productDateStr.length() > 0){
            String str = productDateStr.replace("：",":");
            String[] aa = str.split(":");
            if (aa.length > 1){
                productDateStr = aa[1];
            }else {
                productDateStr = aa[0];
            }
        }

        //批次号
        String batchNoStr = list[5];
        if(batchNoStr != null && batchNoStr.length() > 0){
            String str = batchNoStr.replace("：",":");
            String[] aa = str.split(":");
            if (aa.length > 1){
                batchNoStr = aa[1];
            }else {
                batchNoStr = aa[0];
            }
        }

        //有效期
        String validDateStr = list[6];
        if(validDateStr != null && validDateStr.length() > 0){
            String str = validDateStr.replace("：",":");
            String[] aa = str.split(":");
            if (aa.length > 1){
                validDateStr = aa[1];
            }else {
                validDateStr = aa[0];
            }
        }

        //标签号
        String numStr = list[9];
        if(numStr.startsWith("A")){
            mdItemFind.setTag("有A");
        }else {
            mdItemFind.setTag("有");
        }


        float count = 0;
        QueryWrapper<MdItem> mdItemQueryWrapper = new QueryWrapper<>(mdItemFind);
        if (pageTypeStr != null){
            String aa = pageTypeStr.replace("（",":").replace("：",":");
            aa = aa.split(":")[1];
            mdItemQueryWrapper.like("packing_type",aa);
            count = toFloatValue(aa);
        }


        List<MdItem> mdItems = mdItemService.list(mdItemQueryWrapper);
        if (mdItems == null || mdItems.size() == 0){
            return error("找不到对于的产品记录");
        }

        if (mdItems.size() > 1){
            return error("找到多条记录，无法确定是那个产品");
        }

        MdItem mdItem = mdItems.get(0);
        WmWarehouse warehouse = wmWarehouseService.selectWmWarehouseByWarehouseId(Long.valueOf(stockVo.getWarehouseId()));
        if (warehouse == null){
            return error("仓库不能为空");
        }

        WmItemRecptLine wmItemRecptLine = new WmItemRecptLine();
        wmItemRecptLine.setItemId(mdItem.getItemId());
        wmItemRecptLine.setItemCode(mdItem.getItemCode());
        wmItemRecptLine.setSpecification(mdItem.getSpecification());
        wmItemRecptLine.setUnitOfMeasure(mdItem.getUnitOfMeasure());
        wmItemRecptLine.setItemName(mdItem.getItemName());
        wmItemRecptLine.setBatchCode(batchNoStr);
        wmItemRecptLine.setProductDate(productDateStr);
        wmItemRecptLine.setMeterialCode(numStr);
        wmItemRecptLine.setExpireDate(DateUtils.parseDate(validDateStr));
        wmItemRecptLine.setIsInStock("1");

        WmItemRecptLine findOld = wmItemRecptLineService.getOne(new QueryWrapper<>(wmItemRecptLine));
        if (findOld != null){
            return error("产品已入库");
        }

        wmItemRecptLine.setStatus("1");

        wmItemRecptLine.setWarehouseId(warehouse.getWarehouseId());
        wmItemRecptLine.setWarehouseName(warehouse.getWarehouseName());
        wmItemRecptLine.setWarehouseCode(warehouse.getWarehouseCode());
        wmItemRecptLine.setQuantityRecived(BigDecimal.valueOf(count));



        if (StringUtils.isEmpty(wmItemRecptLine.getStatus())){
            wmItemRecptLine.setStatus("0");
        }
        wmItemRecptLine.setQuantityOut(BigDecimal.valueOf(0));

        wmItemRecptLine.setCreateBy(SecurityUtils.getUsername());
        wmItemRecptLine.setCreateTime(new Date());
        wmItemRecptLineService.addWmItemRecptLine(wmItemRecptLine);
        return AjaxResult.success(wmItemRecptLine);
    }

    /**
     * 新增物料入库单行
     */
    @Log(title = "物料入库单行", businessType = BusinessType.INSERT)
    @PostMapping("/pdaAddPicking")
    @Transactional
    public AjaxResult pdaAddPicking(@RequestBody WmVoPicking picking, HttpServletRequest req)
    {
        String[] list = picking.getText().replace("；",";").split(";");
        WmItemRecptLine mdItemFind = new WmItemRecptLine();
        mdItemFind.setItemName(list[0]); //  产品物料名称
        mdItemFind.setSpecification(list[1]); //规格型号
        mdItemFind.setViscosity(list[2]); // 粘度
        mdItemFind.setMeterialCode(list[8]);  //物料编码
        mdItemFind.setStatus("1"); //状态

        //批次号
        String batchNoStr = list[4];
        if(batchNoStr != null && batchNoStr.length() > 0){
            String str = batchNoStr.replace("：",":");
            String[] aa = str.split(":");
            if (aa.length > 1){
                batchNoStr = aa[1];
            }else {
                batchNoStr = aa[0];
            }
            mdItemFind.setBatchCode(batchNoStr);
        }

//        //  净重：5KG（软）
//        String pageTypeStr = list[6];
//        if(pageTypeStr.contains("（软）")){
//            mdItemFind.setItemName(list[2]+"软");
//        }

//        净重：5KG
        String weightStr = list[6];
        String str2="";
        if(weightStr  != null && weightStr.length() > 0){
            String str = weightStr.replace("：",":");
            String[] aa = str.split(":");
            if (aa.length > 1){
                weightStr = aa[1];
                weightStr=weightStr.trim();
                if(weightStr != null && !"".equals(weightStr)){
                    for(int i=0;i<weightStr.length();i++){
                        if(weightStr.charAt(i)>=48 && weightStr.charAt(i)<=57){
                            str2+=weightStr.charAt(i);
                        }
                    }}
            }else {
                weightStr = aa[0];
                weightStr=weightStr.trim();
                    if(weightStr != null && !"".equals(weightStr)){
                        for(int i=0;i<weightStr.length();i++){
                            if(weightStr.charAt(i)>=48 && weightStr.charAt(i)<=57){
                                str2+=weightStr.charAt(i);
                            }
                        }}
            }
        }

        // 生产日期：2022.11.28
        String productDateStr = list[3];
        if(productDateStr  != null && productDateStr.length() > 0){
            String str = productDateStr.replace("：",":");
            String[] aa = str.split(":");
            if (aa.length > 1){
                productDateStr = aa[1];
            }else {
                productDateStr = aa[0];
            }
        }

        float count = 0;
        LGLeftJoinQueryWrapper<WmItemRecptLine> mdItemQueryWrapper = new LGLeftJoinQueryWrapper<>(mdItemFind,req.getParameterMap(),1,10);
        mdItemQueryWrapper.whereOtherSql("and quantity_recived > quantity_out");
        IPage<JSONObject> mdItems = wmStockOutService.lgPageMapList(mdItemQueryWrapper);

        if (mdItems.getRecords() == null || mdItems.getTotal() == 0){
            return error("找不到对于的产品记录");
        }

        if (mdItems.getTotal() > 1){
            return error("找到多条记录，无法确定是那个产品");
        }
        WmIssueLine wmIssueLine=new WmIssueLine();

        //        获取生产领料单行 IssueId
        WmIssueHeader wmIssueHeader= new WmIssueHeader();
        wmIssueHeader.setIssueName(picking.getIssueName());
        wmIssueHeader.setTaskCode(picking.getTaskCode());
        wmIssueHeader.setTaskId(Long.valueOf(picking.getTaskId()));
        wmIssueHeader.setStatus("PREPARE");
        List<WmIssueHeader> arr = wmIssueHeaderService.selectWmIssueHeaderList(wmIssueHeader);

        if (arr.toString().length()>2){
            wmIssueLine.setIssueId(arr.get(0).getIssueId());
        }else {
            String inputCharacter="";
            wmIssueHeader.setIssueDate(picking.getIssueDate());
            wmIssueHeader.setIssueCode(autoCodeUtil.genSerialCode("ISSUE_CODE",inputCharacter));
            //根据领料单头上的仓库、库区、库位ID设置对应的编号和名称
            if(wmIssueHeader.getWarehouseId()!=null){
                WmWarehouse warehouse = wmWarehouseService.selectWmWarehouseByWarehouseId(wmIssueHeader.getWarehouseId());
                wmIssueHeader.setWarehouseCode(warehouse.getWarehouseCode());
                wmIssueHeader.setWarehouseName(warehouse.getWarehouseName());
            }

            if(StringUtils.isNotNull(wmIssueHeader.getLocationId())){
                WmStorageLocation location = wmStorageLocationService.selectWmStorageLocationByLocationId(wmIssueHeader.getLocationId());
                wmIssueHeader.setLocationCode(location.getLocationCode());
                wmIssueHeader.setLocationName(location.getLocationName());
            }

            if(StringUtils.isNotNull(wmIssueHeader.getAreaId())){
                WmStorageArea area = wmStorageAreaService.selectWmStorageAreaByAreaId(wmIssueHeader.getAreaId());
                wmIssueHeader.setAreaCode(area.getAreaCode());
                wmIssueHeader.setAreaName(area.getAreaName());
            }

            ProTask proTask = proTaskService.getById(wmIssueHeader.getTaskId());
            if (proTask != null){
                proTask.setIsGetMaterials("1");
                proTask.setStatus("已领料");
                proTaskService.updateById(proTask);
                wmIssueHeader.setIssueName(proTask.getTaskName());
            }
            if (wmIssueHeader.getIssueName() == null){
                wmIssueHeader.setIssueName("0");
            }
            wmIssueHeader.setCreateBy(SecurityUtils.getUsername());
            wmIssueHeader.setCreateTime(new Date());
            wmIssueHeaderService.insertWmIssueHeader(wmIssueHeader);
            wmIssueLine.setIssueId(wmIssueHeader.getIssueId());
        }

        wmIssueLine.setItemCode((String) mdItems.getRecords().get(0).get("itemCode"));
        wmIssueLine.setItemId((Long) mdItems.getRecords().get(0).get("itemId"));
        wmIssueLine.setItemName((String) mdItems.getRecords().get(0).get("itemName"));
        wmIssueLine.setWarehouseId((Long) mdItems.getRecords().get(0).get("warehouseId"));
        wmIssueLine.setWarehouseCode((String) mdItems.getRecords().get(0).get("warehouseCode"));
        wmIssueLine.setWarehouseName((String) mdItems.getRecords().get(0).get("warehouseName"));
        wmIssueLine.setItemRecptLineId((Long) mdItems.getRecords().get(0).get("lineId"));
        wmIssueLine.setSpecification((String) mdItems.getRecords().get(0).get("specification"));
        wmIssueLine.setUnitOfMeasure((String) mdItems.getRecords().get(0).get("unitOfMeasure"));
        wmIssueLine.setQuantity(BigDecimal.valueOf(Long.parseLong(str2)));
        wmIssueLine.setLetStepMaterial(String.valueOf(1));
        wmIssueLine.setBatchCode((String) mdItems.getRecords().get(0).get("batchCode"));

       //统计出库
        WmItemRecptLine itemRecptLine = wmItemRecptLineService.getById(wmIssueLine.getItemRecptLineId());
        if (itemRecptLine != null){
            Double ss =  wmIssueLine.getQuantity().doubleValue();
            if (itemRecptLine.getQuantityOut() != null){
                ss += itemRecptLine.getQuantityOut().doubleValue();
            }
            itemRecptLine.setQuantityOut(BigDecimal.valueOf(ss));
            itemRecptLine.setUpdateBy(SecurityUtils.getUsername());
            itemRecptLine.setUpdateTime(new Date());
            wmItemRecptLineService.updateById(itemRecptLine);
        }

        wmIssueLine.setCreateBy(SecurityUtils.getUsername());
        wmIssueLine.setCreateTime(new Date());
        return toAjax(wmIssueLineService.insertWmIssueLine(wmIssueLine));
    }

    /**
     * 补齐日期正确写法
     * @param para
     * @return
     */
    public float toFloatValue(String para){
        int numIndex = 0;
        for(int i=0;i<para.length();i++){
            if(Character.isDigit(para.charAt(i))){
                numIndex++;
            }else {
                break;
            }
        }
        return Float.valueOf(para.substring(0,numIndex)).floatValue();
    }


    /**
     * 修改物料入库单行
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:edit')")
    @Log(title = "物料入库单行", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody WmItemRecptLine wmItemRecptLine)
    {
        if (wmItemRecptLine.getInType().equals("3")
                && wmItemRecptLine.getIsInStock().equals("1")
        ){
            if (wmItemRecptLine.getWarehouseId() == null){
                return AjaxResult.error("入库仓库不能为空");
            }
            if (StringUtils.isEmpty(wmItemRecptLine.getBatchCode())){
                WmIssueLine win = new WmIssueLine();
                win.setAssembleIdToItemRecptLineId(wmItemRecptLine.getLineId());
                QueryWrapper<WmIssueLine> queryWrapper = new QueryWrapper<>(win);
                queryWrapper.select("assemble_id_to_item_recpt_line_id,string_agg ( DISTINCT batch_code, ',' ) AS batch_code ");
                queryWrapper.groupBy("assemble_id_to_item_recpt_line_id");
                win = wmIssueLineService.getOne(queryWrapper);
                if (win == null || StringUtils.isEmpty(win.getBatchCode())){
                    return AjaxResult.error("无法生存批次号");
                }
                wmItemRecptLine.setBatchCode(win.getBatchCode());
            }

        }
        return toAjax(wmItemRecptLineService.updateWmItemRecptLine(wmItemRecptLine));
    }


    /**
     * 修改物料入库单行
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:editNoStock')")
    @Log(title = "物料入库单行", businessType = BusinessType.UPDATE)
    @PutMapping("/editNoStock")
    @Transactional
    public AjaxResult editNoStock(@RequestBody WmItemRecptLine wmItemRecptLine)
    {
        WmWarehouse warehouse = null;
        if(StringUtils.isNotNull(wmItemRecptLine.getWarehouseId())){
            warehouse = wmWarehouseService.selectWmWarehouseByWarehouseId(wmItemRecptLine.getWarehouseId());
            wmItemRecptLine.setWarehouseCode(warehouse.getWarehouseCode());
            wmItemRecptLine.setWarehouseName(warehouse.getWarehouseName());
        }
        if (warehouse == null){
            return error("仓库不能为空");
        }
        if(StringUtils.isNotNull(wmItemRecptLine.getLocationId())){
            WmStorageLocation location = wmStorageLocationService.selectWmStorageLocationByLocationId(wmItemRecptLine.getLocationId());
            wmItemRecptLine.setLocationCode(location.getLocationCode());
            wmItemRecptLine.setLocationName(location.getLocationName());
        }
        if(StringUtils.isNotNull(wmItemRecptLine.getAreaId())){
            WmStorageArea area = wmStorageAreaService.selectWmStorageAreaByAreaId(wmItemRecptLine.getAreaId());
            wmItemRecptLine.setAreaCode(area.getAreaCode());
            wmItemRecptLine.setAreaName(area.getAreaName());
        }

        wmItemRecptLine.setUpdateBy(SecurityUtils.getUsername());
        wmItemRecptLine.setUpdateTime(new Date());

        return toAjax(wmItemRecptLineService.updateSQLModel(wmItemRecptLine));
    }



    /**
     * 删除物料入库单行
     */
    @PreAuthorize("@ss.hasPermi('wm:itemrecptline:remove')")
    @Log(title = "物料入库单行", businessType = BusinessType.DELETE)
	@DeleteMapping("/{lineIds}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] lineIds)
    {
        return toAjax(wmItemRecptLineService.deleteSQLIds(lineIds));
    }

    /*
     * 打印
     */
    @GetMapping("/jimureport/{lineId}")
    public JSONObject Print(@PathVariable String lineId){
        WmItemRecptLine recptLine = wmItemRecptLineService.getById(lineId);
        MdItem mdItem = mdItemService.selectMdItemById(recptLine.getItemId());
        StringBuilder sb = new StringBuilder();
        HashMap<String, String> map = new HashMap<>();
        map.put("row1",mdItem.getItemName()); // 物料名称
        map.put("row2",recptLine.getWarehouseName()); // 仓库名称
        map.put("row3",mdItem.getSpecification()); // 规范型号
        map.put("row4",mdItem.getUnitOfMeasure()); //单位
        map.put("row5",recptLine.getBatchCode()); // 入库批次号
        map.put("row6",sb.append(mdItem.getItemName()).append(",").append(mdItem.getSpecification()).append(",").append(mdItem.getUnitOfMeasure()).toString()); //  扫码显示的内容
        map.put("row7",dictDataService.selectDictLabel("step_material", recptLine.getStatus())); // 状态


        ArrayList list = new ArrayList<>();
        list.add(map);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",list);
        return jsonObject;
    }

    @GetMapping("/printLineIqc")
    public JSONObject printLineIqc(@Param("lineId") Long lineId){
        WmItemRecptLine recptLine = wmItemRecptLineService.getById(lineId);
        MdItem mdItem = mdItemService.getById(recptLine.getItemId());
        QcIqc qcIqc = new QcIqc();
        qcIqc.setRecptId(recptLine.getRecptId());
        qcIqc.setType("1");
        qcIqc.setItemId(recptLine.getItemId());
        List<QcIqc> qcIqcs = iQcIqcService.selectQcIqcList(qcIqc);
        QcIqc qc = new QcIqc();
        if(qcIqcs.size() > 0) {
            qc = qcIqcs.get(0);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",recptLine.getRecptCode());
        jsonObject.put("itemCode",recptLine.getItemCode());
        jsonObject.put("specification",mdItem.getSpecification());
        jsonObject.put("recptDate",DateUtils.dateTime(qc.getReciveDate()));
        jsonObject.put("productionDate",qc.getProductionDate());
        jsonObject.put("batchCode",recptLine.getBatchCode());
        jsonObject.put("validTime",recptLine.getExpireDate()== null?"":DateUtils.dateTime(recptLine.getExpireDate()));
        jsonObject.put("inspectDate",DateUtils.dateTime(qc.getInspectDate()));
        jsonObject.put("quantity",qc.getQuantityRecived());
        ArrayList list = new ArrayList<>();
        list.add(jsonObject);
        JSONObject recptObj = new JSONObject();
        recptObj.put("data",list);
        return recptObj;
    }
    @GetMapping("/printLineIqc/lineList")
    public JSONObject printIqcLine(@Param("lineId") Long lineId){
        WmItemRecptLine recptLine = wmItemRecptLineService.getById(lineId);
        QcIqc qcIqc = new QcIqc();
        qcIqc.setRecptId(recptLine.getRecptId());
        qcIqc.setType("1");
        qcIqc.setItemId(recptLine.getItemId());
        List<QcIqc> qcIqcs = iQcIqcService.selectQcIqcList(qcIqc);
        QcIqc qc = new QcIqc();
        if(qcIqcs.size() > 0) {
            qc = qcIqcs.get(0);
        }
        QcIqcLine qcIqcLine = new QcIqcLine();
        qcIqcLine.setIqcId(qc.getIqcId());
        List<QcIqcLine> qcIqcLines = iQcIqcLineService.selectQcIqcLineList(qcIqcLine);
        for (int i = 0; i < qcIqcLines.size(); i++) {
            qcIqcLines.get(i).setAttr4((i+1l));
        }
        JSONObject dataObj = new JSONObject();
        if(qcIqcLines.size() < 10){
           int size =  10 - qcIqcLines.size();
            for (int i = 0; i < size; i++) {
                qcIqcLines.add(new QcIqcLine());
            }
        }
        List list = new ArrayList();
        for (int i = 0; i < qcIqcLines.size(); i++) {
            QcIqcLine q = qcIqcLines.get(i);
            Map map = new HashMap<>();
            map.put("indexName",q.getIndexName());
            map.put("qcTool",q.getQcTool()==null?"":q.getQcTool());
            map.put("checkMethod",q.getCheckMethod()==null?"":q.getCheckMethod());
            map.put("standerVal",q.getStanderVal());
            map.put("no",q.getAttr4());
            map.put("detectionValue",q.getDetectionValue());
            list.add(map);
        }
        dataObj.put("data",list);
        return dataObj;
    }

}
